package com.wngbms;

import com.mysql.cj.jdbc.JdbcConnection;
import com.mysql.cj.jdbc.MysqlXAConnection;
import com.mysql.cj.jdbc.MysqlXid;

import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * https://blog.csdn.net/m0_45406092/article/details/121429082
 */


/**
 * session1
 *
 * xa start 'g123','001'  ;
 * insert into course (cid, cname, user_id,cstatus) values (15,"php", 1, 1);
 * xa end 'g123','001';
 *
 * xa PREPARE 'g123','001';
 * xa commit 'g123','001';
 * xa rollback 'g123','001';
 */

/**
 * session2
 *
 * xa start 'g123','002'  ;
 * insert into course (cid, cname, user_id,cstatus) values (16,"php", 1, 1);
 * xa end 'g123','002';
 *
 * xa PREPARE 'g123','002';
 * xa commit 'g123','002';
 * xa rollback 'g123','002';
 */
public class XAJdbc {

    public static void main(String[] args) throws SQLException, XAException {
        Connection conn1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
        XAConnection xaConn1 = new MysqlXAConnection((JdbcConnection) conn1, true);
        XAResource rm1 = xaConn1.getXAResource();

        Connection conn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
        XAConnection xaConn2 = new MysqlXAConnection((JdbcConnection) conn2, true);
        XAResource rm2 = xaConn2.getXAResource();

        byte[] gtrid = "g12345".getBytes(StandardCharsets.UTF_8);
        int formatId = 1;

        byte[] bqual1 = "b0001".getBytes(StandardCharsets.UTF_8);
        Xid xid1 = new MysqlXid(gtrid, bqual1, formatId);
        // start
        rm1.start(xid1, XAResource.TMNOFLAGS);
        // exec
        PreparedStatement ps1 = conn1.prepareStatement("insert into course (cname, user_id,cstatus) values (\"php\", 1, 1)");
        ps1.execute();
        // end
        rm1.end(xid1, XAResource.TMSUCCESS);

        byte[] bqual2 = "b0002".getBytes(StandardCharsets.UTF_8);
        Xid xid2 = new MysqlXid(gtrid, bqual2, formatId);
        // start
        rm2.start(xid2, XAResource.TMNOFLAGS);
        // exec
        PreparedStatement ps2 = conn2.prepareStatement("insert into course (cname, user_id,cstatus) values (\"php\", 1, 1)");
        ps2.execute();
        // end
        rm2.end(xid2, XAResource.TMSUCCESS);

        // prepare
        int rm1_prepare = rm1.prepare(xid1);
        int rm2_prepare = rm2.prepare(xid2);

        // commit
        if (rm1_prepare == XAResource.XA_OK && rm2_prepare == XAResource.XA_OK) {
            rm1.commit(xid1, false);
            rm2.commit(xid2, false);
        }
        // rollback
        else {
            rm1.rollback(xid1);
            rm2.rollback(xid2);
        }
    }

}
